<?php

namespace App\Models;

use App\Models\Contract\SerializeDatetime;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

class Setting extends Model
{
    use HasFactory, SerializeDatetime;

    protected $fillable = [
        'key', 'value', 'type'
    ];

    /**
     * @param string $string
     * @return string|array|mixed
     */
    public static function get(string $key = '')
    {
        if (empty($key)) {
            $settings = [];
            $records = Setting::all();
            foreach ($records as $record) {
                $key = $record->getAttribute('key');
                $value = $record->getAttribute('value');
                if ($record->getAttribute('type') == 'json') {
                    $value = json_decode($value, true);
                }
                $settings[$key] = $value;
            }
            return $settings;
        } else {
            $record = Setting::query()->where('key', $key)->first();
            if (!$record) {
                return '';
            }
            $value = $record->getAttribute('value');
            if ($record->getAttribute('type') == 'json') {
                return json_decode($value, true);
            } else {
                return $value;
            }
        }
    }

    public static function apps(): array
    {
        $keys = [
            'player_group_url', 'player_group_qrcode', 'service_url', 'service_qrcode',
            'app_name', 'app_code', 'app_version',
            'invites', 'exchange_rate', 'max_redpack_amount', 'withdrawals',
            'earnings', 'group_entry', 'hot_update_url', 'app_id', 'qq_key', 'ip_limit','mch_id','app_logo'
        ];
        $records = Setting::query()->whereIn('key', $keys)->get();
        $settings = [];
        foreach ($records as $record) {
            $key = $record->getAttribute('key');
            $value = $record->getAttribute('value');
            if ($record->getAttribute('type') == 'json') {
                $value = json_decode($value, true);
            }
            $settings[$key] = $value;
        }
        foreach ($keys as $v) {
            $settings[$v] = $settings[$v] ?? '';
        }
        $settings['agreement'] = url('agreement');
        $settings['privicy'] = url('privicy');

        return $settings;
    }

    public static function set(string $key, $value)
    {
        $presets = array_keys(self::defaults());
        if (!in_array($key, $presets)) {
            return;
        }

        $record = Setting::query()->where('key', $key)->first();
        if (!$record) {
            Setting::query()->create([
                'key' => $key,
                'value' => $value,
                'type' => 'string',
            ]);
            return;
        }
        $oldValue = $record->getAttribute('value');
        if ($record->getAttribute('type') == 'json') {
            $elements = json_decode($oldValue, true);
            if ($key == 'withdrawals') {
                $updateValue = [];
                foreach (array_values($value) as $idx => $val) {
                    if (isset($val['_remove_']) && $val['_remove_'] == 1) {
                        continue;
                    }
                    $e = Arr::only($val, ['id', 'value', 'label', 'limit']);
                    $e['id'] = sprintf('%s', 1001 + $idx);
                    $e['label'] = $e['label'] ?? '';
                    $e['limit'] = $e['limit'] ?? 0;
                    $updateValue[] = $e;
                }
                if (!empty($updateValue)) {
                    $sorted = collect($updateValue)->sortBy('value')->values()->all();
                    foreach ($sorted as $pidx => &$s) {
                        $s['id'] = 1001 + $pidx;
                    }
                    $updateValue = $sorted;
                }
            } else if ($key == 'earnings') {
                $ratios = $value['b_to_a_ratios'] ?? [];
                $newRatios = [];
                foreach ($ratios as $ratio) {
                    if (isset($ratio['_remove_']) && $ratio['_remove_'] == 1) {
                        continue;
                    }
                    $e = Arr::only($ratio, ['b_value', 'a_value', 'condition', 'ratio']);
                    $e['a_value'] = $e['a_value'] ?? 0;
                    $e['ratio'] = $e['ratio'] ?? 0;

                    $newRatios[] = $e;
                }
                $updateValue = array_merge(Arr::except($elements, ['b_to_a_ratios']), Arr::except($value, ['b_to_a_ratios']));
                if (isset($value['b_to_a_ratios'])) {
                    $updateValue['b_to_a_ratios'] = $newRatios;
                }
            } else {
                $updateValue = array_merge($elements, $value);
            }
            $updateValue = json_encode($updateValue, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        } else {
            $updateValue = $value;
        }

        Setting::query()->where('key', $key)->update([
            'value' => $updateValue,
        ]);
    }

    public static function defaults(): array
    {
        return [
            'app_name' => config('services.program.title'),
            'app_code' => config('services.program.code'),
            'app_version' => config('services.program.version'),
            'hot_update_url' => '',
            'app_id' => '',
            'app_secret' => '',
            'qq_key' => '',
            // 广告媒体ID
            'media_id' => '1000000000000000000-3',
            'max_ecpm' => 0,
            'invites' => [
                // 友盟U-Link
                'ulinkid' => config('services.program.ulinkid'),
                'appkey' => config('services.program.appkey'),
                'download_app_url' => config('services.program.download_app_url'),
                'local_download_url' => '',
            ],
            // 1元兑换金币数量
            'exchange_rate' => 10000,
            // 红包最大值
            'max_redpack_amount' => 5000,
            // 提现金额审核
            'withdraw_limit' => 0.3,
            'withdraw_count_per_day' => 3,
            'withdrawsinfo' => '',
            'group_sub_rate' => 0,
            // 提现列表
            'withdrawals' => [
                [
                    'id' => "1001",
                    'value' => "0.3",
                    'label' => '新人专项',
                    'limit' => "1",
                ],
                [
                    'id' => "1002",
                    'value' => "1.0",
                    'label' => '每日一次',
                    'limit' => "1",
                ],
                [
                    'id' => "1003",
                    'value' => "2.0",
                    'label' => '',
                    'limit' => "0",
                ],
                [
                    'id' => "1004",
                    'value' => "5.0",
                    'label' => '',
                    'limit' => "0",
                ],
                [
                    'id' => "1005",
                    'value' => "10.0",
                    'label' => '',
                    'limit' => "0",
                ],
                [
                    'id' => "1006",
                    'value' => "20.0",
                    'label' => '',
                    'limit' => "0",
                ],
                [
                    'id' => "1007",
                    'value' => "50.0",
                    'label' => '',
                    'limit' => "0",
                ],
                [
                    'id' => "1008",
                    'value' => "100.0",
                    'label' => '',
                    'limit' => "0",
                ]
            ],
            // 推广奖励设置
            'earnings' => [
                // 每邀请1人所获得的最大收益，单位元
                'max_per_guest' => 38,
                // 下级提现上级用户获得收益比例（累计提现）
                'b_to_a_ratios' => [
                    [
                        'b_value' => 1,
                        'a_value' => 1,
                        'condition' => '=',
                        'ratio' => 0
                    ],
                    [
                        'b_value' => 2,
                        'a_value' => 1.5,
                        'condition' => '=',
                        'ratio' => 0
                    ],
                    [
                        'b_value' => 5,
                        'a_value' => 2.5,
                        'condition' => '=',
                        'ratio' => 0
                    ],
                    [
                        'b_value' => 10,
                        'a_value' => 3,
                        'condition' => '=',
                        'ratio' => 0
                    ],
                    [
                        'b_value' => 50,
                        'a_value' => 12,
                        'condition' => '=',
                        'ratio' => 0
                    ],
                    [
                        'b_value' => 100,
                        'a_value' => 0,
                        'condition' => '=',
                        'ratio' => 0.05
                    ],
                ]
            ],
            'payment' => [
                'kylin' => [
                    'company_id' => config('services.payment.kylin.company_id'),
                    'sign_type' => config('services.payment.kylin.sign_type'),
                    'remark' => '',
                    'private_key' => config('services.payment.kylin.private_key'),
                ]
            ],
            'privicy' => '隐私政策...',
            'agreement' => '用户协议...',
            'bank' => [
                'account_id' => config('services.oem.account_id'),
                'balance' => config('services.oem.balance'),
                'lowest_balance' => config('services.oem.lowest_balance'),
            ],
            'group_entry' => config('services.group_entry'),
            'group' => [
                'enabled' => '0',
                // 开团价格
                'price' => 50,
                // 最低人数
                'lowest_member' => 50,
                // 团长最低提现金额
                'withdrawable' => 100,
                // 成员(间推)收益比例
                'invite_prize' => 0.1,
                // 专属(直推)收益比例
                'direct_prize' => 0.2,
                // 从下级团长收益比例
                'child_leader_price' => 0.05,

            ],
            'advanced_group' => [
                'advanced_lowest_member' => 100,
                'advanced_price' => 75,
                // 高级： 成员(间推)收益比例
                'advanced_invite_prize' => 0.12,
                // 高级：专属(直推)收益比例
                'advanced_direct_prize' => 0.3,
                // 高级：从下级团长收益比例
                'advanced_child_leader_price' => 0.03,
            ],
            'whitelist' => config('services.whitelist'),
            'player_group_url' => '',
            'player_group_qrcode' => '',
            'service_url' => '',
            'service_qrcode' => '',
            'coin_starter' => 0,
            'app_logo' => '',
        ];
    }
}
